//
//

const fs = require('fs');

function routes(app) {
  app.all('*', function(req, res) {

    let path = req.path.replace(/\/+/g, '/').slice(1);

    // 网站首页，直接渲染，提高性能
    if (!path) {
      res.render('index');
      return;
    }

    path = path.endsWith('/') ? path.slice(0, -1).split('/') : path.split('/');
    let exists1 = fs.existsSync('controller/' + path[0] + '/' + path[1] + '.js');
    let exists2 = fs.existsSync('controller/home/' + path[0] + '.js');

    if(exists1) {
      let ctl = require('../controller/' + path[0] + '/' + path[1]);
      ctl[path[2]] ? ctl[path[2]](req, res) : res.render('common/404');

    } else if(exists2) {
      let ctl = require('../controller/home/' + path[0]);
      ctl[path[1]] ? ctl[path[1]](req, res) : res.render('common/404');

    } else {

      res.render('common/404')
    }
  });
}


module.exports = routes;
